package com.itany.shop.service.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParameterUtil;

/**
 * @Author:石小俊
 * @Date:2022/11/15 15:50
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class UserServiceImpl implements UserService {

    private UserDao userDao = (UserDao) ObjectFactory.getObject("userDao");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        // 参数保护
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(phone) || ParameterUtil.isNull(address)){
            // 只要有任意一个参数值为空,则抛出异常,表示用户输入的数据有误
            throw new RequestParameterErrorException("请求参数有误");
        }

        // 判断用户名是否存在
        User selectUser = userDao.selectByUsername(username);
        if(selectUser != null){
            throw new UserExistException("该用户名已经被注册");
        }
        // 如果用户名可用,则开始注册
        User user = new User(username, MD5Util.md5(password),phone,address);
        userDao.insertUser(user);
    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        // 参数保护
        if(ParameterUtil.isNull(username) || ParameterUtil.isNull(password)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        // 由于注册的时候,密码加密后存储到数据库
        // 在进行登录的时候,我们同样需要将密码加密后再去数据库进行查询
        // 在调用dao方法的时候,将密码加密后传递过去
        User user = userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(null == user){
            throw new UserNotExistException("用户名或密码错误");
        }
        return user;
    }
}
